#include "stdafx.h"
#include "CTimer.h"

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
Summary: Default constructor.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
CTimer::CTimer()
{
    QueryPerformanceFrequency( (LARGE_INTEGER *)&g_ticksPerSecond );

    g_currentTime = g_lastTime = g_lastFPSUpdate = 0;
    g_numFrames = 0;
    g_runningTime = g_timeElapsed = g_fps = 0.0f;
    g_FPSUpdateInterval = g_ticksPerSecond >> 1;
    g_timerStopped = TRUE;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
Summary: Starts the timer.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void CTimer::Start()
{
    if ( !g_timerStopped )
    {
        // Already started
        return;
    }
    QueryPerformanceCounter( (LARGE_INTEGER *)&g_lastTime );
    g_timerStopped = FALSE;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
Summary: Stops the timer.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void CTimer::Stop()
{
    if ( g_timerStopped )
    {
        // Already stopped
        return;
    }
    INT64 stopTime = 0;
    QueryPerformanceCounter( (LARGE_INTEGER *)&stopTime );
    g_runningTime += (float)(stopTime - g_lastTime) / (float)g_ticksPerSecond;
    g_timerStopped = TRUE;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
Summary: Updates the timer. Calculates the time elapsed since the last Update call.
Updates the frames per second and updates the total running time.     
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void CTimer::Update()
{
    if ( g_timerStopped )
    {
        return;
    }

    // Get the current time
    QueryPerformanceCounter( (LARGE_INTEGER *)&g_currentTime );
    
    g_timeElapsed = (float)(g_currentTime - g_lastTime) / (float)g_ticksPerSecond;
    g_runningTime += g_timeElapsed;

    // Update FPS
    g_numFrames++;
    if ( g_currentTime - g_lastFPSUpdate >= g_FPSUpdateInterval )
    {
        float currentTime = (float)g_currentTime / (float)g_ticksPerSecond;
        float lastTime = (float)g_lastFPSUpdate / (float)g_ticksPerSecond;
        g_fps = (float)g_numFrames / (currentTime - lastTime);

        g_lastFPSUpdate = g_currentTime;
        g_numFrames = 0;
    }

    g_lastTime = g_currentTime;
}